package com.ryan.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ryan.security.browser.support.SimpleResponse;
import com.ryan.security.core.properties.LoginType;
import com.ryan.security.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by kaimin on 1/1/2019.
 * time : 22:20
 * 登录成之后会被调用,写过之后，需要在应用中告知容器，要用自定义的，不要用默认的
 */
@Component("simpleAuthenticationFailHandler")
@Slf4j
//public class SimpleAuthenticationFailHandler implements AuthenticationFailureHandler{
public class SimpleAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler{
    //也是灵活的让客户端自己决定是跳转还是返回json

    //登录成之后会被调用

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    /**
     *
     * @param request
     * @param response
     * @param exception 封装的认证异常信息 session，用户信息等
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        log.info("登录失败");
        if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=UTF-8");
//            response.getWriter().write(objectMapper.writeValueAsString(exception));//这个是打印全部堆栈信息
            response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(exception.getMessage())));//只返回错误消息
        } else {
            super.onAuthenticationFailure(request,response,exception);
        }

//        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
//        response.setContentType("application/json;charset=UTF-8");
//        response.getWriter().write(objectMapper.writeValueAsString(exception));

    }
}
